package com.ruoyi.business.listener;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.ruoyi.business.domain.BuyerInfo;
import com.ruoyi.business.service.BuyerInfoService;
import com.ruoyi.business.utils.BadRequestException;
import lombok.extern.slf4j.Slf4j;

import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;


/**
 * @author ty
 */
@Slf4j
public class BuyerInfoExcelListener extends AnalysisEventListener<Map<Integer, String>> {

    private final BuyerInfoService buyerInfoService;

    public List<String> errorList = new ArrayList<>();
    private final List<BuyerInfo> saveList = new ArrayList<>();

    private static final SimpleDateFormat SDF = new SimpleDateFormat("yyyy-MM-dd");

    public BuyerInfoExcelListener(BuyerInfoService buyerInfoService) {
        this.buyerInfoService = buyerInfoService;
    }

    @Override
    public void invoke(Map<Integer, String> data, AnalysisContext context) {
        int currentRowNum = context.readRowHolder().getRowIndex() + 1;
        log.info("第{}行解析数据: {}", currentRowNum, JSONUtil.toJsonStr(data));
        try {
            saveList.add(parseRowToBuyerInfo(data, currentRowNum));
        } catch (Exception e) {
            log.error("第{}行解析异常：{}", currentRowNum, e.getMessage(), e);
            errorList.add(String.format("第%s行错误：%s", currentRowNum, e.getMessage()));
        }
    }


    private BuyerInfo parseRowToBuyerInfo(Map<Integer, String> data, int rowNum) throws Exception {
        List<String> list = new ArrayList<>();
        for (int i = 0; i <= 9; i++) {
            String val = data.get(i);
            list.add(val != null ? val.trim() : "");
        }

        BuyerInfo info = new BuyerInfo();
        info.setRowNum(rowNum);

        String widStr = list.get(0);
        if (StrUtil.isBlank(widStr)) {
            throw new BadRequestException("客户编号为空，导入数据无效");
        }
        try {
            info.setWid(Long.valueOf(widStr));
        } catch (NumberFormatException e) {
            throw new BadRequestException("客户编号格式错误：" + widStr);
        }
        info.setPhone(StrUtil.blankToDefault(list.get(1), null));
        info.setUserNickName(StrUtil.blankToDefault(list.get(2), null));
        info.setName(StrUtil.blankToDefault(list.get(3), null));
        info.setBuyerRemark(StrUtil.blankToDefault(list.get(4), null));
        info.setCreateTime(parseDate(list.get(5)));
        info.setCreateBy(StrUtil.blankToDefault(list.get(6), null));
        info.setUpdateTime(parseDate(list.get(7)));
        info.setUpdateBy(StrUtil.blankToDefault(list.get(8), null));
        return info;
    }

    private Date parseDate(String dateStr) throws ParseException {
        return StrUtil.isNotBlank(dateStr) ? new Timestamp(SDF.parse(dateStr).getTime()) : null;
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        if (CollUtil.isEmpty(saveList)) {
            return;
        }
        if (CollUtil.isNotEmpty(errorList)) {
            return;
        }
        try {
            log.info("共{}条数据，开始入库", saveList.size());
            buyerInfoService.batchInsertOrUpdateByImport(saveList);
            log.info("入库成功！");
        } catch (Exception e) {
            log.error("数据入库异常：{}", e.getMessage(), e);
            errorList.add("数据入库异常：" + e.getMessage());
        }
    }

}
